package graphic;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.net.InetAddress;
import java.util.Vector;

import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JViewport;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;

public class UsersPanel extends JScrollPane {

	protected static UsersPanel USERSPANEL;

	JTable usersTable;
	DefaultTableModel usersTableModel;

	public UsersPanel() {

		this.createTable();

		super.getViewport().setScrollMode(JViewport.BACKINGSTORE_SCROLL_MODE);
		super.setViewportView(this.usersTable);

		super.setPreferredSize(new Dimension(200, 300));
	}

	protected void createTable() {
		this.usersTableModel = new DefaultTableModel() {
			@Override
			public boolean isCellEditable(int row, int column) {
				return false;
			}
		};

		this.usersTableModel.setColumnIdentifiers(UsersPanel.getTableHeader());

		this.usersTable = new JTable(this.usersTableModel);
		this.usersTable.setFont(new Font("Comic Sans MS", Font.BOLD, 15));
		this.usersTable.setForeground(Color.black);
		this.usersTable.setGridColor(Color.black);

		this.usersTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);		
	}

	protected static Vector<String> getTableHeader() {
		Vector<String> header = new Vector<String>();
		header.add("User Id");
		header.add("Ip");

		return header;
	}

	public void addUser(String userId, InetAddress ip)
	{
		this.usersTableModel.insertRow(this.usersTable.getRowCount(), new Object[] { userId, ip.getHostAddress() });		
	}

	public void removeUser(String userId) {
		for (int i = 0; i < this.usersTable.getRowCount(); i++)
			if (this.usersTable.getValueAt(i, 0).equals(userId))
				this.usersTableModel.removeRow(i);
	}
	
	public static synchronized UsersPanel getInstance() {
		if (USERSPANEL == null)
			USERSPANEL = new UsersPanel();
		return USERSPANEL;
	}

}
